package tech.wetech.admin3.controller;

import jakarta.validation.constraints.NotBlank;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.wetech.admin3.sys.model.AooUser;
import tech.wetech.admin3.sys.service.*;
import tech.wetech.admin3.util.AooJwtUtil;
import tech.wetech.admin3.util.CustomResponse;


@RestController
@RequestMapping("/aoo")
@Slf4j
public class AooLoginController {
  private AooUserService aooUserService;
  private AooTokenService aooTokenService;
  private AooPhoneCodeService phoneCodeService;
  private AooJwtUtil jwtUtil;

  public AooLoginController(
    AooUserService aooUserService,
    AooTokenService aooTokenService,
    AooPhoneCodeService phoneCodeService,
    AooJwtUtil jwtUtil
  ){
    this.aooUserService=aooUserService;
    this.aooTokenService=aooTokenService;
    this.phoneCodeService = phoneCodeService;
    this.jwtUtil = jwtUtil;
  }

  @PostMapping("/aoologin")
  public ResponseEntity<?> aoologin(@RequestBody AoologinRequest aoologinRequest){
    String email = aoologinRequest.email();
    String password = aoologinRequest.password();
    AooUser user = aooUserService.findByEmail(email);   // 查询数据库
    boolean flag = aooUserService.checkPassword(email, password);

    if(flag){
      String role = user.getRole();
      Integer status = user.getStatus();

      String token = jwtUtil.generateToken(email, status, role);
      //添加token
      user.setToken(token); // 储存到token表后是否还需要放在user里？

      aooTokenService.saveAooToken(token); // 储存token

      return ResponseEntity.ok(new CustomResponse.r1("登陆成功", true, user));
    }
    return ResponseEntity.ok(new CustomResponse.r1("用户名或密码错误", false, ""));
  }

  @PostMapping("/aoologinph")
  public ResponseEntity<?> aoologinph(@RequestBody AoologinphRequest aoologinphRequest){
    String phone = aoologinphRequest.phone();
    String vericode = aoologinphRequest.vericode();

    AooUser user = aooUserService.findByPhone(phone);   // 查询数据库
    if(user == null){
      return ResponseEntity.ok(new CustomResponse.r1("用户未注册", false, ""));
    }

    boolean flag = phoneCodeService.verifyCode(phone, vericode);
    if (!flag) {
      return ResponseEntity.ok(new CustomResponse.r1("验证码错误或已过期", false, ""));
    }

    String email = user.getEmail();
    String role = user.getRole();
    Integer status = user.getStatus();

    String token = jwtUtil.generateToken(email, status, role);
    // 添加token
    user.setToken(token);

    aooTokenService.saveAooToken(token);

    return ResponseEntity.ok(new CustomResponse.r1("登陆成功", true, user));
  }

  record AoologinRequest(@NotBlank String email,
                         @NotBlank String password){}

  record AoologinphRequest(@NotBlank String phone,
                         @NotBlank String vericode){}
}
